class_name ObjectPool extends Object
## 对象池


## 池
var _pool:Array[Node] = []
## 场景对象
var _scene: PackedScene
## 根节点
var _root_node: Node
## 当对象池没有可用对象时，是否自动增长
var _auto_increasement: bool

## 构造函数
func _init(scene: PackedScene, root_node: Node, 
		pool_size: int = 100, auto_increasement: bool = true)->void:
	_scene = scene
	_root_node = root_node
	_auto_increasement = auto_increasement
	for _i in pool_size:
		_create_object()


## 创建对象，并添加到对象池中
func _create_object()->Node:
	var new_node: Node = _scene.instantiate()
	_pool.append(new_node)
	_root_node.add_child(new_node)
	return new_node


## 从对象池取出一个对象
func take()->Node:
	var node: Node = null
	if not _pool.is_empty():
		node = _pool.pop_back()
	elif _auto_increasement:
		node = _create_object()
	return node


## 将对象归还到对象池
func restore(node:Node)->void:
	_pool.append(node)


## 清空对象池
func clear()->void:
	for node:Node in _pool:
		node.queue_free()
